package com.zyf.service.audio;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class HandleKugouTempBP {


    /**
     * 将缓存音乐转换为mp3
     *
     * @param musicFolder
     * @param exeFilePath
     * @return
     * @throws Exception
     */
    public String handleKugouMusic(String musicFolder, String exeFilePath) throws Exception {
        //酷狗缓存音乐
        List<File> musicFiles = FileUtil.loopFiles(musicFolder, tempfile -> tempfile.isFile() && tempfile.getName().endsWith(".kgtemp"));
        //父级文件夹
        String exeParentPath = new File(exeFilePath).getParent();
        for (File file : musicFiles) {
            //先复制文件到父级文件夹
            copyFile(file.getAbsolutePath(), exeParentPath);
            String newPath = exeParentPath + File.separator + file.getName();
            //文件重命名
            String newNameFilePath = newPath.replace(".kgtemp", ".kgm");
            new File(newPath).renameTo(new File(newNameFilePath));
            //删除file
            if (file.exists()) {
                file.delete();
            }
        }
        return "成功";
    }

    /**
     * 获取音乐的歌曲名并更改文件名
     *
     * @param musicFolder
     * @return
     * @throws Exception
     */
    public String handleMusicName(String musicFolder) throws Exception {
        //酷狗音乐
        List<File> musicFiles = FileUtil.loopFiles(musicFolder, tempfile -> tempfile.isFile() && tempfile.getName().endsWith(".mp3"));
        //父级文件夹
        for (File file : musicFiles) {
            try {
                String parentPath=file.getParent();
                String newName= getSongName(file.getAbsolutePath());
                System.out.println("这是新的"+newName);
                //文件重命名
                String newNameFilePath = parentPath+File.separator+newName+".mp3";
                File newFile=new File(newNameFilePath);
                boolean res=new File(file.getAbsolutePath()).renameTo(newFile);
                //删除file
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
        return "成功";
    }


    public  String getSongName(String path) throws Exception {
        String songName ="";
        String singer ="";
        RandomAccessFile raf =null;
        try {
            raf = new RandomAccessFile(path, "rw");
            byte buf[] = new byte[128];
            byte buf1[] = new byte[4];
            raf.seek(raf.length() - 128);
            raf.read(buf);
            raf.seek(45);// 指针往前走45个字节，从第46个字节开始
            raf.read(buf1);
            if (buf.length != 128) {
                System.err.println("MP3标签信息数据长度不合法!");
            }
            if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
                System.err.println("MP3标签信息数据格式不正确!");
            }
            String srcsongName = new String(buf, 3, 30, "gbk");
            songName = srcsongName.replace("\u0000", "");
            System.out.println("歌名：" + songName);
            String srcsinger = new String(buf, 33, 30, "gbk");
            singer = srcsinger.replace("\u0000", "");
            System.out.println("作者：" + singer);
            String Album = new String(buf, 63, 30, "gbk");
            System.out.println("专辑：" + Album);
            System.out.println("文件长度：" + raf.length());

            // 将字节转化为二进制字符串
            String s1 = String.format("%8s", Integer.toBinaryString(buf1[0] & 0xFF)).replace(' ', '0');
            String s2 = String.format("%8s", Integer.toBinaryString(buf1[1] & 0xFF)).replace(' ', '0');
            String s3 = String.format("%8s", Integer.toBinaryString(buf1[2] & 0xFF)).replace(' ', '0');
            String s4 = String.format("%8s", Integer.toBinaryString(buf1[3] & 0xFF)).replace(' ', '0');
            String c = s1 + s2 + s3 + s4;
            char sc[] = c.toCharArray();
            System.out.println("音频版本：" + AudioVersion(sc[11], sc[12]));
            System.out.println("采样频率：" + SampleFrequency(sc[11], sc[12], sc[20], sc[21]));
            System.out.println("声道模式：" + ChannelMode(sc[24], sc[25]));

        } catch (IOException e) {
            System.err.println("发生异常:" + e);
            e.printStackTrace();
        }finally {
            raf.close();
        }
        return songName+"-"+singer;
    }

    //判断音频版本
    public static String AudioVersion(char a, char b) {
        String result = "";
        if ('0' == a && '0' == b)
            result = "MPEG 2.5";
        else if ('0' == a && '1' == b)
            result = "保留";
        else if ('1' == a && '0' == b)
            result = "MPEG 2";
        else if ('1' == a && '1' == b)
            result = "MPEG 1";
        return result;
    }

    //判断采样频率
    public static int SampleFrequency(char a1, char b1, char a, char b) {
        int f = 0;
        if (AudioVersion(a1, b1) == "MPEG 1" && '0' == a && '0' == b)
            f = 44100;
        if (AudioVersion(a1, b1) == "MPEG 2" && '0' == a && '0' == b)
            f = 22050;
        if (AudioVersion(a1, b1) == "MPEG 2.5" && '0' == a && '0' == b)
            f = 11025;
        if (AudioVersion(a1, b1) == "MPEG 1" && '0' == a && '1' == b)
            f = 48000;
        if (AudioVersion(a1, b1) == "MPEG 2" && '0' == a && '1' == b)
            f = 24000;
        if (AudioVersion(a1, b1) == "MPEG 2.5" && '0' == a && '1' == b)
            f = 12000;
        if (AudioVersion(a1, b1) == "MPEG 1" && '1' == a && '0' == b)
            f = 32000;
        if (AudioVersion(a1, b1) == "MPEG 2" && '1' == a && '0' == b)
            f = 16000;
        if (AudioVersion(a1, b1) == "MPEG 2.5" && '1' == a && '0' == b)
            f = 8000;
        return f;
    }

    //判断声道模式
    public static String ChannelMode(char a, char b) {
        String result = "";
        if ('0' == a && '0' == b)
            result = "立体声";
        else if ('0' == a && '1' == b)
            result = "联合立体声";
        else if ('1' == a && '0' == b)
            result = "双声道";
        else if ('1' == a && '1' == b)
            result = "单声道";
        return result;
    }


    private void copyFile(String sourceFile, String desfolder) {
        // 源文件路径
        Path source = Paths.get(sourceFile);
        // 目标文件夹路径
        Path destinationDir = Paths.get(desfolder);
        // 目标文件路径
        Path destination = destinationDir.resolve(source.getFileName());
        try {
            // 确保目标文件夹存在
            Files.createDirectories(destinationDir);
            // 使用Files.copy()方法复制文件到目标文件夹
            Files.copy(source, destination);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void execWindowProcess(String exeFilePath) throws Exception {
        BufferedReader stdInput = null;
        BufferedReader stdError = null;
        try {
            // 这里"your-executable.exe"是你要执行的exe文件的路径
            Process process = Runtime.getRuntime().exec(exeFilePath);
            // 获取输入流和错误流，可以用于读取程序的输出和错误信息
            stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            // 读取标准输出
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            // 读取错误输出
            while ((s = stdError.readLine()) != null) {
                System.out.println("Error: " + s);
            }
            // 等待程序执行结束
            int exitVal = process.waitFor();
            System.out.println("Exited with error code : " + exitVal);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stdInput != null) {
                stdInput.close();
            }
            if (stdError != null) {
                stdError.close();
            }
        }


    }


}
